import { Avatar, Button, Divider, MenuProps, App } from 'antd';
import Dropdown, { DropdownProps } from 'antd/es/dropdown/dropdown';
import React, { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { NavLink } from 'react-router-dom';

import { IconButton, SvgIcon } from '@/components/icon';
import { useLoginStateContext } from '@/pages/sys/login/providers/LoginStateProvider';
import { useRouter } from '@/router/hooks';
import { useUserInfo, useUserActions } from '@/store/userStore';
import { useThemeToken } from '@/theme/hooks';
import { RightOutlined } from '@ant-design/icons';
import { useSettings } from '@/store/settingStore';
import { ThemeLayout } from '@/types/enum';
import { logout } from '@/pages/auth/authUtils';
import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';
import AdviceModal from '@/pages/components/modal/AdviceModal';
import LicenseConfirmModal from '@/pages/components/modal/LicenseConfirm';
import ResetPasswordModal from '@/pages/components/modal/ResetPasswordModal';

import JoyrideGuide from '@/pages/components/joyride-guide-v2';
import LicenseModal from '@/pages/components/modal/LicenseModal';
import UserInfoModal from '@/pages/components/modal/UserInfoModal';

import appService from '@/api/services/appService';
import userService from '@/api/services/userService';
import { useInitializeData, useConfig } from '@/store/configStore';
import { useTourActions, useIsTourStart, useIsTourGuide } from '@/store/tourStore';
import { sha256 } from 'js-sha256';

import Cookies from 'js-cookie';
import { jwtDecode } from 'jwt-decode';
import usePermission from '@/hooks/event/usePermission';
import ImageDisplay from '@/components/work-modal/components/ImageDisplay';
const { VITE_TOKEN: VITETOKEN } = import.meta.env;

interface AccountProps {
  isShow?: boolean;
}
/**
 * Account Dropdown
 */
export default function Account({ isShow = false }: AccountProps) {
  const { message } = App.useApp();
  const { username, email, avatar, role, id: userId } = useUserInfo();
  const { themeLayout } = useSettings();
  const { t } = useTranslation();
  const [logoutVisible, setLogoutVisible] = useState(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const { colorBgElevated, boxShadowSecondary, colorPrimary } = useThemeToken();
  const initializeData = useInitializeData();
  const { VITE_LICENSE_FLAG: LICENSEFLAG } = import.meta.env;
  const licenseFlag = LICENSEFLAG === 'true' ? true : false;
  const router = useRouter();
  const { isAdmin, isSuperAdmin } = usePermission();
  const { setUserToken, setUserInfo } = useUserActions();
  const userInfo = useUserInfo();
  useEffect(() => {
    if (!username) {
      router.push('/login');
    }
  }, [username]);

  useEffect(() => {
    const token = Cookies.get(VITETOKEN);
    if (token) {
      const decodedToken = jwtDecode(token);
      let mergeUser = {
        ...userInfo,
        ...decodedToken,
      };

      setUserInfo(mergeUser);
      setUserToken({ accessToken: token, refreshToken: token });
    }
  }, [Cookies.get(VITETOKEN)]);

  const isRoot = username == 'root';

  const { setIsTourStart, setIsTourGuide } = useTourActions();
  const isTourStart = useIsTourStart();
  const isTourGuide = useIsTourGuide();
  const [isLicenseModalOpen, setIsLicenseModalOpen] = useState(false);
  const [isUserInfoModalOpen, setIsUserInfoModalOpen] = useState(false);

  const handleLicenseCancel = () => {
    setIsLicenseModalOpen(false);
  };
  const handleUserInfoCancel = () => {
    setIsUserInfoModalOpen(false);
  };

  const [isActivateConfirmModalOpen, setIsActivateConfirmModalOpen] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [actIcon, setActIcon] = useState<number>(0);
  const [showAdvice, setShowAdvice] = useState(false);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  // 标记是否有模态框打开，用于阻止hover触发
  const [modalOpen, setModalOpen] = useState(false);

  const { license_edition, allowLocalAccount } = useInitializeData();
  const isLocalAccount = useMemo(() => {
    if (!license_edition) {
      return false
    } else {
      return allowLocalAccount ? true : false
    }
  }, [allowLocalAccount, license_edition]);

  // 监听所有模态框状态变化
  useEffect(() => {
    const isAnyModalOpen =
      logoutVisible ||
      passwordModalVisible ||
      isLicenseModalOpen ||
      isUserInfoModalOpen ||
      isActivateConfirmModalOpen ||
      isTourStart ||
      isTourGuide ||
      showAdvice;
    setModalOpen(isAnyModalOpen);
  }, [
    logoutVisible,
    passwordModalVisible,
    isLicenseModalOpen,
    isUserInfoModalOpen,
    isActivateConfirmModalOpen,
    isTourStart,
    isTourGuide,
    showAdvice,
  ]);

  const contentStyle: React.CSSProperties = {
    backgroundColor: colorBgElevated,
    borderRadius: '10px',
    boxShadow: boxShadowSecondary,
    width: '120px',
  };

  const menuStyle: React.CSSProperties = {
    boxShadow: 'none',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
  };

  const dropdownRender: DropdownProps['dropdownRender'] = (menu) => (
    <div style={contentStyle}>
      {React.cloneElement(menu as React.ReactElement, { style: menuStyle })}
    </div>
  );

  const handleLogoutConfirm = () => {
    setLogoutVisible(false);
    logout();
  };

  const handleAdviceCancel = () => {
    setActIcon(0);
    setInputValue('');
    setShowAdvice(false);
  };

  const handleAdviceConfirm = async (actId: number, text: string) => {
    appService
      .surveySubmit({
        content: {
          title: t('page.homePage.postTitleText'),
          feedback: text,
          score: actId,
        },
      })
      .then((res) => {
        console.log(res);
        message.success(t('page.homePage.submitSuccess'));
        setActIcon(0);
        setInputValue('');
        setShowAdvice(false);
      });
  };

  const handleDropdownVisibleChange = (flag: boolean) => {
    // 如果有模态框打开，就不允许下拉菜单打开
    if (modalOpen && flag) {
      return;
    }
    setDropdownOpen(flag);
  };

  const items: MenuProps['items'] = [
    ...(isShow &&
      (isAdmin ||
        isSuperAdmin ||
        initializeData.is_knowledge_manager ||
        initializeData.is_knowledge_reviewer)
      ? [
        {
          key: '0',
          label: <button className="text-center">{t('page.homePage.backWorkspace')}</button>,
          style: { padding: '10px' },
          onClick: () => {
            //这里清空掉appId和shareId
            router.push('/worklayouts/');
          },
        },
      ]
      : []),
    ...(isLocalAccount ? [
      {
        key: '1',
        label: <button className="text-center">{t('page.homePage.changeInformation')}</button>,
        style: { padding: '10px' },
        onClick: () => {
          setPasswordModalVisible(true);
          setDropdownOpen(false);
        },
      }] : []),
    {
      key: '6',
      label: <button className="text-center">{t('page.homePage.userInformation')}</button>,
      style: { padding: '10px' },
      onClick: () => {
        setIsUserInfoModalOpen(true);
      },
    },
    {
      key: '2',
      label: <button className="text-center ">{t('page.homePage.userFeedback')}</button>,
      style: { padding: '10px' },
      onClick: () => {
        if (licenseFlag && !initializeData?.is_license_valid) {
          setIsActivateConfirmModalOpen(true);
        } else {
          setInputValue('');
          setActIcon(0);
          setShowAdvice(true);
        }
        setDropdownOpen(false);
      },
    },
    // 仅当用户名为root时显示license菜单项
    ...(isRoot
      ? [
        {
          key: '3',
          label: <button className="text-center ">{t('page.homePage.license')}</button>,
          style: { padding: '10px' },
          onClick: () => {
            setIsLicenseModalOpen(true);
            setDropdownOpen(false);
          },
        },
      ]
      : []),
    // {
    //   key: '4',
    //   label: <button className="text-center ">{t('page.homePage.beginnerGuide')}</button>,
    //   style: { padding: '10px' },
    //   onClick: () => {
    //     router.push('/worklayouts');
    //     setIsTourStart(false);
    //     setIsTourGuide(true);
    //     setDropdownOpen(false);
    //   },
    // },
    {
      key: '5',
      label: <button className="text-center ">{t('page.homePage.logOut')}</button>,
      style: { padding: '10px', color: 'red' },
      onClick: () => {
        setLogoutVisible(true);
        setDropdownOpen(false);
      },
    },
  ];

  useEffect(() => {
    setDropdownOpen(false);
  }, []);

  return (
    <Dropdown
      menu={{ items }}
      placement={'topRight'}
      trigger={['hover']}
      dropdownRender={dropdownRender}
      align={{ offset: [120, 0] }}
      open={dropdownOpen}
      onOpenChange={handleDropdownVisibleChange}
      disabled={modalOpen}
    >
      <div className={`jr-step-v2-4 jr2-step-v2-3 jr3-step-v2-2 ${themeLayout === ThemeLayout.Vertical ? 'ml-2' : ''} flex cursor-pointer items-center justify-center py-2`}>
        {/* <Avatar
          className="h-10 w-10 transform-none cursor-pointer px-0 hover:scale-105"
          style={{ backgroundColor: colorPrimary }}
        >
          {username && username[0]}
        </Avatar> */}
        {avatar ? (
          <ImageDisplay
            src={avatar || ''}
            alt="avatar"
            containerClassName='rounded-[50%] w-[35px] h-[35px] border-none'
          />
        ) : (
          <SvgIcon icon="ic-avatar" size="35" className="mr-2 rounded-md" />
        )}
        {themeLayout === ThemeLayout.Vertical && (
          <div className="ml-2">
            <div style={{ fontSize: '14px' }}>{username}</div>
            <div className="text-[#AAAFC2]" style={{ fontSize: '11px' }}>
              {role?.name}
            </div>
          </div>
        )}
        {themeLayout === ThemeLayout.Vertical && (
          <div className="ml-auto">
            <Button
              type="text"
              icon={<RightOutlined size={10} className=" text-text-3 hover:text-[#4989F6]" />}
            ></Button>
          </div>
        )}
        <DeleteConfirmModal
          visible={logoutVisible}
          text="确定要退出登录吗?"
          onCancel={() => {
            setLogoutVisible(false);
          }}
          onConfirm={handleLogoutConfirm}
          onConfirmText="退出登录"
        />
        <AdviceModal
          visible={showAdvice}
          actIcon={actIcon}
          setActIcon={setActIcon}
          inputValue={inputValue}
          setInputValue={setInputValue}
          onCancel={handleAdviceCancel}
          onConfirm={handleAdviceConfirm}
        />
        <LicenseConfirmModal
          visible={isActivateConfirmModalOpen}
          onCancel={() => {
            setIsActivateConfirmModalOpen(false);
          }}
        />
        <JoyrideGuide />
        <LicenseModal visible={isLicenseModalOpen} onCancel={handleLicenseCancel} />
        <UserInfoModal visible={isUserInfoModalOpen} onCancel={handleUserInfoCancel} />
        <ResetPasswordModal
          visible={passwordModalVisible}
          onCancel={() => setPasswordModalVisible(false)}
        />
      </div>
    </Dropdown>
  );
}
